<template>
	<splitpanes class="default-theme">
		<pane size="100">
			<el-container class="jp-container">
				<el-header v-if="searchVisible">
					<div class="left-panel">
						<el-form
							:inline="true"
							class="query-form"
							ref="searchForm"
							:model="searchForm"
							@keyup.enter="refreshList()"
							@submit.prevent
						>

							<el-form-item
								label="分工会/协会"
								prop="postDTO.id"
								v-if="currentUser.name == '管理员'"
							>
								<el-select
									v-model="searchForm.postDTO.id"
									style="width:  200px"
									placeholder="请选择"
								>
									<el-option
										v-for="role in postList"
										:key="role.id"
										:label="role.name"
										:value="role.id"
									>
									</el-option>
								</el-select>
							</el-form-item>

							<el-form-item
								label="组织"
								prop="postDTO.id"
								v-if="currentUser.name !== '管理员'"
							>
								<el-select
									v-model="searchForm.postDTO.id"
									style="width: 200px"
									
									placeholder="请选择"
								>
									<el-option
										v-for="role in currentUserPost"
										:key="role.id"
										:label="role.name"
										:value="role.id"
									>
									</el-option>
								</el-select>
							</el-form-item>

							<el-form-item
								label="职位"
								prop="roleDTO.id"
								v-if="currentUser.name == '管理员'"
							>
								<el-select
									v-model="searchForm.roleDTO.id"
									style="width:  200px"
									placeholder="请选择"
								>
									<el-option
										v-for="role in roleList"
										:key="role.id"
										:label="role.name"
										:value="role.id"
									>
									</el-option>
								</el-select>
							</el-form-item>
							<el-form-item prop="no" label="工号：">
								<el-input
									v-model="searchForm.no"
									placeholder="请输入工号"
									clearable
								></el-input>
							</el-form-item>
						
							<el-form-item prop="selectJoinTime" label="入会时间：">
								<el-input
									v-model="searchForm.selectJoinTime"
									placeholder="年月日之间请使用-间隔"
									clearable
								></el-input>
							</el-form-item>
							<!-- <el-form-item prop="status" label="是否在职：">
								<el-input
									v-model="searchForm.status"
									placeholder="是或否"
									clearable
								></el-input>
							</el-form-item> -->
							<el-form-item
								label="在职"
								prop="status"
							>
								<el-select
									v-model="searchForm.status"
									style="width:  200px"
									placeholder="请选择"
								>
									<el-option
										v-for="status in [{value: '是',label: '是',},{value: '否',label: '否',}]"
										:key="status.value"
										:label="status.label"
										:value="status.value"
									>
									</el-option>
								</el-select>
							</el-form-item>
						</el-form>
					</div>
					<div class="right-panel">
						<el-button
							type="primary"
							class="round"
							@click="refreshList()"
							icon="search"
						>
							查询</el-button
						>
						<el-button
							type="default"
							@click="resetSearch()"
							icon="refresh-right"
							>重置</el-button
						>
					</div>
				</el-header>
				<el-main class="nopadding page2">
					<div class="jp-table">
					
						<div class="jp-table-body">
							<vxe-table
								border="inner"
								auto-resize
								resizable
								height="auto"
								:loading="loading"
								size="small"
								ref="userTable"
								show-header-overflow
								show-overflow
								highlight-hover-row
								:print-config="{}"
								:import-config="{
									importMethod: importMethod,
									types: ['csv', 'xls', 'xlsx'],
									remote: true,
								}"
								:export-config="{
									remote: true,
									filename: `用户数据${moment(
										new Date()
									).format('YYYY-MM-DD')}`,
									sheetName: '用户数据',
									exportMethod: exportMethod,
									types: ['xlsx'],
									modes: ['current', 'selected', 'all'],
								}"
								@sort-change="sortChangeHandle"
								:sort-config="{ remote: true }"
								:data="dataList"
							>
								<vxe-column
									type="checkbox"
									width="40px"
								></vxe-column>
							
								<vxe-column
									title="登录名"
									field="loginName"
									
								>
									<template #default="{ row }">
										<el-link
											v-bind:class="{
												'disabled-user':
													row.loginFlag === '0',
											}"
											type="primary"
											:underline="false"
											v-if="
												hasPermission('sys:user:view')
											"
											@click="view(row.id)"
											>{{ row.loginName }}</el-link
										>
										<span
											v-bind:class="{
												'disabled-user':
													row.loginFlag === '0',
											}"
											v-else
											>{{ row.loginName }}</span
										>
									</template>
								</vxe-column>

								<vxe-column title="姓名" field="name" >
								
								</vxe-column>
								<vxe-column title="工号" field="no" ></vxe-column>
								<vxe-column
									title="学校"
									sort-by="c.name"
									field="companyDTO.name"
									
								>
									<template #default="{ row }">
										{{
											row.companyDTO &&
											row.companyDTO.name
										}}
									</template>
								</vxe-column>
								<vxe-column
									title="学院"
									sort-by="o.name"
									field="officeDTO.name"
								
								>
									<template #default="{ row }">
										{{
											row.officeDTO && row.officeDTO.name
										}}
									</template>
								</vxe-column>
								<vxe-column title="职位" field="roleDTO.name" ></vxe-column>
								<vxe-column title="在职" field="status" ></vxe-column>
								
								<vxe-column
									title="操作"
									width="200px"
									fixed="right"
									align="center"
								>
									<template #default="{ row }">
										<el-button
											v-if="
												hasPermission('sys:user:view')
											"
											type="primary"
											text
											icon="view-filled"
											@click="view(row.id)"
											>查看</el-button
										>
										
									</template>
								</vxe-column>
							</vxe-table>
							<vxe-pager
								background
								size="small"
								:current-page="tablePage.currentPage"
								:page-size="tablePage.pageSize"
								:total="tablePage.total"
								:page-sizes="[
									10,
									20,
									100,
									1000,
									{ label: '全量数据', value: 1000000 },
								]"
								:layouts="[
									'PrevPage',
									'JumpNumber',
									'NextPage',
									'FullJump',
									'Sizes',
									'Total',
								]"
								@page-change="currentChangeHandle"
							>
							</vxe-pager>
						</div>
					</div>
				</el-main>
			</el-container>
		</pane>
	</splitpanes>
	<user-form ref="userForm" @refreshDataList="refreshList"></user-form>
	<div class="chart">
		<el-container class="jp-container">
			<el-main class="nopadding page2">
				<div style="display: flex; flex-wrap: wrap; width: 100%; overflow: hidden;">
					<div style="flex-grow: 1;flex-basis: 200px;">
						<!-- <sexRatio></sexRatio> -->
						<div>
							<div style="display: flex; justify-content: center;margin-top: 30px;">
								<h3>
									性别比
								</h3>
							</div>
							<div>
								<v-chart style="height:170px;" :option="optionSex"></v-chart>
							</div>
						</div>
					</div>
					
					<div style="flex-grow: 1;flex-basis: 200px;">
						<div >
							<div style="display: flex; justify-content: center;margin-top: 30px;">
								<h3>
									在职状态
								</h3>
							</div>
							<div >
								<v-chart style="height:170px;" :option="optionStatus"></v-chart>
							</div>
						</div>
					</div>
					<div style="flex-grow: 1;flex-basis: 200px;" v-if="searchForm.postDTO.id != ''">
						<div style="width: 80%;margin: 0 auto;">
							<div style="display: flex;justify-content: center;">
								<h3>
									本月组织人数增长趋势
								</h3>
							</div>
							<div style="margin: 30px auto; ">
								<v-chart style="height:300px;" :option="optionIncrease"></v-chart>
							</div>
						</div>
					</div>
				</div>
			</el-main>
		</el-container>
	</div>
</template>

<script>
import { Splitpanes, Pane } from "splitpanes";
import "splitpanes/dist/splitpanes.css";
import UserForm from "./UserForm";
import userInformation from "@/api/servicecenter/userInformation";
import officeService from "@/api/sys/officeService";
import postService from "@/api/sys/postService";
import roleService from "@/api/sys/roleService";

import sexRatioService from "@/api/organization/sexRatioService.js";

import * as echarts from 'echarts'
import increaseService from '@/api/organization/increaseService.js'



export default {
	data() {
		return {
			currentUser:{},
			companyTreeData:[],
			roleList:[],
			postList: [],
			currentUserPost:[],
			//性别比
			charSexData:[
				{
					value: 0,
					name: "男",
				},
				{
					value: 0,
					name: "女",
				},
			],
			optionSex: {},
			//增长趋势
			chartIncreaseData:['0','0','0','0'],
			dayIncrease: ['7','14','21','28'],
			optionIncrease: {},

			//在职状态
			charStatusData:[
				{
					value: 1,
					name: "在职",
				},
				{
					value: 1,
					name: "下岗",
				},
			],
			optionStatus: {},

			statusOptions : [
				{
					value: '是',
					label: '是',
				},
				{
					value: '否',
					label: '否',
				},
			],

			searchForm: {
				loginName: "",
				name: "",
				no:"",
				selectJoinTime: "",
				status: "",

				companyDTO: {
					id: "",
				},
				officeDTO: {
					id: "",
				},
				postDTO:{
					id:"",
				},
				roleDTO:{
					id:"",
				}
			},
			searchVisible: true,
			filterText: "",
			dataList: [],
			officeTreeData: [],
			tablePage: {
				total: 0,
				currentPage: 1,
				pageSize: 10,
				orders: [{ column: "a.create_time", asc: false }],
			},
			loading: false,
		};
	},
	components: { Splitpanes, Pane, UserForm },
	mounted() {
		this.$nextTick(() => {
			// 将表格和工具栏进行关联
			const $table = this.$refs.userTable;
			const $toolbar = this.$refs.userToolbar;
			$table.connect($toolbar);
			//获取用户工会信息
			this.selectList();
		});
		this.refreshTree();
		this.refreshList();
	},
	
	watch: {
		filterText(val) {
			this.$refs.officeTree.filter(val);
		},
	},
	methods: {
		selectList(){
			Promise.all([
					roleService.list({ current: 1, size: -1 }),
					postService.list({ current: 1, size: -1 }),
					officeService.treeData({ type: 1 }),
				]).then((result) => {
					this.roleList = result[0].records;
					this.postList = result[1].records;
					this.companyTreeData = result[2];
				});
		},
		getCurrentUser() {
			var userInfo = this.$TOOL.data.get("USER_INFO");
			return userInfo;
		},
		//性别比
		initSex(){
			sexRatioService.selectSexRatio(this.searchForm.postDTO.id)
			.then((data)=>{
				this.charSexData[0].value=data.male
				this.charSexData[1].value=data.female
				this.initSexChart()
			});
		},
		initSexChart(){
			this.optionSex= {
						textStyle: {
						fontFamily: 'Inter, "Helvetica Neue", Arial, sans-serif',
					},
					title: {
						text: "",
						left: "center",
					},
					tooltip: {
						trigger: "item",
						formatter: "{a} <br/>{b} : {c} ({d}%)",
					},
					legend: {
						orient: "vertical",
						left: "left",
						data: ["男", "女"],
					},
					series: [
						{
							name: "性别比",
							type: "pie",
							radius: "55%",
							center: ["50%", "60%"],
							//数据绑定
							data: this.charSexData,
							emphasis: {
								itemStyle: {
									shadowBlur: 10,
									shadowOffsetX: 0,
									shadowColor: "rgba(0, 0, 0, 0.5)",
								},
							},
						},
					],
				}
		},

		//增长趋势
		initIncrease(){
			increaseService.selectTrend(this.searchForm.postDTO.id)
			.then((data)=>{
            this.chartIncreaseData=data.list
            this.initIncreaseChart()
			});
		},
		initIncreaseChart(){
			this.optionIncrease = {
               //   backgroundColor:"#0F285C",
               grid: {
                  containLabel: true,
                  top: 30,
                  right: 15,
                  bottom: 0,
                  left: 15
               },
               tooltip: {
                  trigger: "axis",
                  axisPointer: {
                     type: 'shadow'
                  },
                  formatter: params => {
                     const {
                        name,
                        data,
                     } = params[0];
                     return `
                        <span style="font-size: 14px;font-family: Source Han Sans CN-Medium;font-weight: 500;color: #FFFFFF;margin-bottom:12px;">${name}</span>
                        <sapn style="font-size: 14px;font-family: Source Han Sans CN-Medium;font-weight: 500;color: #FFFFFF;margin-bottom:4px;">：${data} 次</span>
                     `
                  },
                  extraCssText: 'opacity: 0.8;background-color:#050F1B;padding:16px;box-shadow: 1px 6px 15px 1px rgba(0,0,0,0.13);border-radius: 4px;filter: blur(undefinedpx);border:none;'
               },
               xAxis: {
                  // 类目轴
                  type: "category",
                  data: ['7', '14', '21', '28'],
                  axisTick: {
                     show: false //隐藏X轴刻度
                  },
                  axisLine: {
                     lineStyle: {
                        color: "#CCCCCC"
                     }
                  },
                  axisLabel: {
                     show: true,
                     textStyle: {
                        color: '#000',
                        fontSize: 14,
                        fontFamily: 'Source Han Sans CN-Regular',
                     }
                  },
               },
               yAxis: {
                  type: 'value',
                  name: "",
                  nameTextStyle: {
                     color: 'rgba(0,0,0,0.65)',
                     fontSize: 14,
                     fontFamily: 'Source Han Sans CN-Regular',
                     align: "left",
                     verticalAlign: "center",
                  },
                  axisLabel: {
                     color: 'rgba(0,0,0,0.65)',
                     textStyle: {
                        fontSize: 14
                     },
                  },
                  axisLine: {
                     show: false,
                     lineStyle: {
                        color: 'rgba(223, 223, 223, 1)',
                     }
                  },
                  axisTick: {
                     show: false
                  },
                  splitLine: {
                     lineStyle: {
                        color: 'rgba(223, 223, 223, 1)',
                        type: "dashed",
                     }
                  }
               },
               series: [
                  {
                     type: "bar",
                     barWidth: "50%",
                     showBackground: true,
                     backgroundStyle: {
                        color: "transparent"
                     },
                     itemStyle: {
                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                           { offset: 0, color: "#4B87FFFF" },
                           { offset: 1, color: "#82BCFFFF" }
                        ])
                     },
                     data: this.chartIncreaseData
                  }
               ]
            };
		},
		//在职状态
		initStatus(){
			sexRatioService.selectStatusRatio(this.searchForm.postDTO.id)
			.then((data)=>{
				this.charStatusData[0].value=data.on
				this.charStatusData[1].value=data.off
				this.initStatusChart()
			});
		},
		initStatusChart(){
			this.optionStatus = {
                    tooltip: {
                        trigger: 'item',
                        formatter: '{b}: {c} ({d}%)',
                    },
                    legend: [
                        {
                            top: '5%',
                            orient: 'vertical',
                            left: '5%',
                            itemWidth: 16,
                            itemHeight: 16,
                            icon: 'circle',
                            itemGap: 20,
                            textStyle: {
                            color: 'black',
                            fontSize: 15,
                            padding: [0, 0, 0, 10],
                            },
                            data: ['在职', '下岗'],
                        }
                        
                    ],
                    grid: {
                        containLabel: true,
                    },
                    series: [
                        {
                        type: 'pie',
                        radius: ['30%', '60%'],
                        center: ['50%%', '60%'],
                        color: [
                            '#2CAA3F',
                            '#FFB933',
                            
                        ],
                        label: {
                            position: 'outside',
                            show: true,
                            color: 'black',
                            textBorderWidth: 1,
                            fontSize: 16,
                            formatter: function (params) {
                            if (params.name !== '') {
                                return params.name ;
                            }
                            },
                        },
                        labelLine: {
                            show: true,
                            length2: 10,
                            length: 10,
                        },
                        data:this.charStatusData,
                        },
                    ],
                    }

		},

		filterNode(value, data) {
			if (!value) return true;
			return data.name.indexOf(value) !== -1;
		},
		// 获取数据列表
		refreshList() {
			this.loading = true;
			this.currentUser=this.getCurrentUser()
			this.searchForm.officeDTO.id=this.currentUser.officeDTO.id
			userInformation.queryByUserId(this.currentUser.id,"")
			.then((data)=>{
				this.currentUserPost=data
				if(this.currentUser.name !=='管理员' && this.searchForm.postDTO.id === ''){
					this.searchForm.postDTO.id=this.currentUserPost[0].id
				}
				//加载图表
				this.initSex();
				if(this.searchForm.postDTO.id !== ''){
					this.initIncrease();
				}
				this.initStatus();
				userInformation
					.list({
						current: this.tablePage.currentPage,
						size: this.tablePage.pageSize,
						orders: this.tablePage.orders,
						...this.searchForm,
					})
					.then((data) => {
						this.dataList = data.records;
						this.tablePage.total = data.total;
						this.loading = false;
					});
			})	
		},
		refreshTree() {
			officeService.treeData().then((data) => {
				this.officeTreeData = data;
			});
		},
		// 当前页
		currentChangeHandle({ currentPage, pageSize }) {
			this.tablePage.currentPage = currentPage;
			this.tablePage.pageSize = pageSize;
			this.refreshList();
		},
		// 排序
		sortChangeHandle(obj) {
			this.tablePage.orders = [];

			if (obj.order != null) {
				this.tablePage.orders = [
					{
						column:
							obj.column.sortBy ||
							this.$utils.toLine(obj.property),
						asc: obj.order === "asc",
					},
				];
			} else {
				this.tablePage.orders = [
					{ column: "a.create_time", asc: false },
				];
			}
			this.refreshList();
		},
		
		// 查看
		view(id) {
			this.$refs.userForm.init("view", id,this.searchForm.postDTO.id);
		},
		
		handleNodeClick(data) {
			if (data.type === "1") {
				this.searchForm.companyDTO.id = data.id;
				this.searchForm.officeDTO.id = "";
			} else {
				this.searchForm.companyDTO.id = "";
				this.searchForm.officeDTO.id = data.id;
			}
			this.refreshList();
		},
		resetSearch() {
			this.searchForm.selectJoinTime = "";
			this.searchForm.no= "";
			this.searchForm.postDTO.id= "";
			this.searchForm.roleDTO.id= "";
			this.searchForm.status= "";
			this.postList=[]
			this.roleList=[]
			this.filterText = "";
			// this.$refs.officeTree.setCurrentKey(null);
			// this.$refs.searchForm.resetFields();
			this.refreshList();
			this.selectList()
		},
	},
};
</script>
<style scoped>
.disabled-user {
	text-decoration: line-through;
	color: #999;
}
.chart{
	overflow: hidden;
	margin: 0 1% 1% 1%;
}
</style>
